study.ajaxQueue = [];
study.host = '{{host}}';

$.ajax = function(args) {
	args.attempts = 0;
	study.ajaxQueue.push(args);
};
$.get = $.astound_ajax_get;
$.getJSON = $.astound_ajax_getJSON;
jQuery.fn.load = jQuery.fn.astound_ajax_load;

study.serializeTagArray = function(ar) {
	var ar2 = [];
	for (var i = 0, j = ar.length; i < j; i++) {
		var str = ar[i];
		str = encodeURIComponent(str);
		ar2.push(str)
	}
	return ar2;
};

study.serialize = function(ar) {
	var ar2 = [];
	var t = {};
	for (var i = 0, j = ar.length; i < j; i++) {
		var obj = ar[i];
		if (typeof(t[obj.name]) == 'undefined') {
			t[obj.name] = [];
		}
		var t2 = t[obj.name];
		t2.push(obj.value);
	}
	for (var i = 0, j = ar.length; i < j; i++) {
		var obj = ar[i];
		if (typeof(t[obj.name]) != 'undefined') {
			var t2 = t[obj.name];
			t2 = t2.join(',');
			ar2.push(encodeURIComponent(obj.name) + '=' + encodeURIComponent(t2));
			delete(t[obj.name]);
		}
	}
	return ar2.join("&");
};

study.ajax_do = function() {
	study.adjustHeight();
	if (study.ajaxQueue.length == 0) {
		setTimeout(study.ajax_do,2);
		return;
	}
	var args = study.ajaxQueue[0];
	var params = {};
	if (args.dataType == 'json') {
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	} else {
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	}
	params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
	if ((args.type == 'GET') && (typeof(args.data) == 'undefined')) {
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
	} else {
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		var post_data = '';
		if (args.data) {
			var tags = '';
			if (typeof(args.data.tags) != 'undefined') {
				args.data.tags = study.serializeTagArray(args.data.tags);
			}
			if (typeof(args.data.length) == 'undefined') {
				post_data = gadgets.io.encodeValues(args.data);
			} else {
				post_data = study.serialize(args.data);
			}
		}
		params[gadgets.io.RequestParameters.POST_DATA] = post_data;
	}

	var url = args.url;
	if (url.search(/^https?:/i) == -1) {
		url = 'http://{{host}}' + args.url;
	}
	var sep = '?';
	if (url.indexOf("?") > -1) {
		sep = '&';
	}
	var ts = new Date().getTime();
	url = [url, sep, 'nocache=', ts].join("");
	var callback = function(r) {
		// if failed, retry
		if ((r.errors.length > 0) || (parseInt(r.rc) != 200)) {
			if (args.attempts > 20) {
				if (study.host.search(/dyndns/) >= 0) {
					$('#content').html('<p>makeRequest failed 20 times?  Look at the log file.</p>');
				} else {
					$('#content').html('<p>We apologize for your inconvenience.  An error happened.  We will investigate it.  Please try again later.</p>');
				}
				study.ajaxQueue = [];
				setTimeout(study.ajax_do,1);
				return;
			}
			args.attempts = args.attempts + 1;
			study.ajax_do();
		} else {
			study.ajaxQueue.shift();
			if (args.success) {
				args.success(r.data);
			}
			study.ajax_do();
		}
	};
	gadgets.io.makeRequest(url,callback,params);
};

study.shareURL_callback = function(data) {
	study.renderSetList(data,true);
};
study.shareURL = function(e) {
	var url = $('#shareURL_input').val();
	url = jQuery.trim(url);
	if ((url != '') && (url.search(/\bshare\b/) > -1)) {
		var that = this;
		$(this).val('Please wait').disable();
		$.ajax({'url': url, 'success': function() { $('#shareURL_input').val(''); $(that).val('Study').enable(); study.refreshSetList(true); }});
	} else {
		$('#shareURLContainerDiv_error').text('Please provide a valid URL and click the Study button again.');
	}
};

study.getDisplayName = function(type,callback) {
	var req = opensocial.newDataRequest();
	if (type == 'viewer') {
		req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER),'viewer');
	} else {
		req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.OWNER),'owner');
	}
	req.send(callback);
};

study.social_user_update_display_name = function() {
	study.getDisplayName('viewer',function(r) {
			var viewer = r.get('viewer').getData();
			var displayName = viewer.getDisplayName();
			$.ajax({'url': '/social/user/updateDisplayName.json', 'type': 'POST', 'data': {'displayName': displayName}});
			});
};

study.gotoCanvasView = function(e) {
	e.preventDefault();
	var canvas = gadgets.views.getSupportedViews()['canvas'];
	gadgets.views.requestNavigateTo(canvas);
	return false;
};

study.init = function() {
	console.log("study.init invoked");
	study.social = true;
	study.socialView = gadgets.views.getCurrentView().getName();
	study.social_user_update_display_name();
	if (study.socialView == 'canvas') {
		setTimeout(study.ajax_do,1);
		$('#header_bar').removeClass('hideMe');
		$("#addset").click(study.renderAddSetForm);
		$("#usageHistoryLink").click(study.displayUsageHistoryPage);
		$('#searchbtn').click(study.search);
		$('#homeLink').click(function(e) { e.preventDefault(); study.refreshSetList(true); return false;});
		// study.fetchTemplate('studyTableTemplate');
	} else {
		setTimeout(study.ajax_do,1);
		$('#shareURLContainerDiv').removeClass('hideMe');
		$('#shareURL_form').submit(study.doNothing_handler);
		$('#shareURL_btn').click(study.shareURL);
		$('<a href="/" id="switchToCanvas">Go to canvas view!</a>').appendTo('#shareURLContainerDiv');
		$('#switchToCanvas').click(study.gotoCanvasView);
		// study.fetchTemplate('studyTableTemplate');
	}
	study.refreshSetList(true);
	$('#notificationOuterContainer').jqm({'modal': true});
};

//gadgets.util.registerOnLoadHandler(study.init);
$(document).ready(study.init);
